<template>
  <div class="app-container">
    <el-button type="success" icon="el-icon-document-add" style="margin-left: 10px" @click="drawerAddUser = true">
      添加用户
    </el-button>

    <el-table :data="tableData.filter(data => !search || data.username.toLowerCase().includes(search.toLowerCase()))"
      style="width: 100%">
      <el-table-column label="编号" prop="userId"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="手机号" prop="phoneNumber"></el-table-column>
      <el-table-column label="地址" prop="address"></el-table-column>
      <el-table-column align="right">
        <template slot="header" slot-scope="scope">
          <el-input v-model="search" size="mini" placeholder="输入关键字搜索" />
        </template>
        <template slot-scope="scope">
          <el-button size="mini" type="danger" @click="handleEdit(scope.$index, scope.row)">删除</el-button>
          <el-button size="mini" @click="update()">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" @prev-click="prevClick"
        @next-click="nextClick" :current-page="currentPage" :page-sizes="[5, 10, 20, 50]" :page-size="5"
        layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>
    <div class="app-container">
      <el-drawer title="编辑基本信息" :visible.sync="drawerAddUser" :direction="direction" :before-close="handleClose"
        size="40%">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="mini" class="demo-ruleForm">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phoneNumber">
            <el-input v-model="ruleForm.phoneNumber"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="ruleForm.address"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="cancelForm">取消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')">确认</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>
    </div>
  </div>
</template>

<script>
  import {
    userList,
    updateUserFlagById,
    deleteUser,
    add
  } from '@/api/user';

  export default {
    data() {
      return {
        flag: 'Y',
        tableData: [],
        currentPage: 1,
        pageNum: 1,
        pageSize: 5,
        total: 0,
        search: '',
        formInline: {
          lxmc: '',
          lxpri: 0,
          xybz: ''
        },
        ruleForm: {
          name:'',
          phoneNumber:'',
          address:''
        },
        rules: {
          lxmc: [{
              required: true,
              message: '请输入类型名称',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 5,
              message: '长度在2 到 5 个字符',
              trigger: 'blur'
            }
          ],
          xybz: [{
            required: true,
            message: '请选择是否启用',
            trigger: 'change'
          }],
          lxbz: [{
            required: true,
            message: '请填写类型备注',
            trigger: 'blur'
          }]
        },
        drawerAddUser: false,
        direction: 'rtl',
        loading: false
      };
    },
    methods: {
      getList() {
        this.loading = true;
        userList(this.pageNum, this.pageSize).then(res => {
          console.info('resdsfsad==>', res);
          this.tableData = res.list;
          this.total = res.total;
          this.loading = false;
        });
      },
      stateFormat(row, column) {
        this.btnname = row[column.property] == 'Y' ? '禁用' : '启用';
        return row[column.property] == 'Y' ? '可用' : '不可用';
      },
      dateFormat(row, column) {
        return row[column.property].replace('T', ' ');
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.pageNum = val;
        this.getList();
      },
      prevClick(val) {
        this.pageNum = val;
        this.getList();
      },
      nextClick(val) {
        this.pageNum = val;
        this.getList();
      },
      getListByFlag() {
        this.loading = true;
        userList(this.flag).then(res => {
          this.listLoading = false;
        });
      },
      handleEdit(index, row) {
        console.log(index, row);
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteUser(row.userId).then(res => {
            this.loading = true;
            if (res) {
              this.$message({
                type: 'success',
                message: '删除成功!',
              });
              this.getList();
            } else {
              this.$message({
                type: 'error',
                message: '删除失败!'
              });
            }
          }).catch(() => {
            this.loading = false;
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        });
      },
      handleDisable(index, row) {
        console.log(index, row.id);
        if (row.id == 1) {
          this.$message({
            type: 'success',
            message: '当前用户不可禁用'
          });
          return;
        }
        this.$confirm('此操作将更改用户名称为' + row.username + '的应用状态, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true;
          // 执行禁用方法
          updateUserFlagById({
            id: row.id,
            flag: row.flag
          }).then(res => {
            this.listLoading = false;
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: res.message
              });
              this.getList();
            } else {
              this.$message({
                type: 'error',
                message: res.message
              });
            }
          });
        }).catch(() => {
          this.loading = false;
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      },
      handleClose(done) {
        if (this.loading) {
          return;
        }
        this.$confirm('确定要提交表单吗？').then(_ => {
          this.loading = true;
          this.timer = setTimeout(() => {
            done();
            // 动画关闭需要一定的时间
            setTimeout(() => {
              this.loading = false;
            }, 400);
          }, 2000);
        }).catch(_ => {});
      },
      cancelForm() {
        this.loading = false;
        this.drawerAddUser = false;
        clearTimeout(this.timer);
      },
      submitForm(formName) {

        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.loading = true;
            add(this.ruleForm).then(res => {
              this.loading = false;
              if (res>=1) {
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                });
                this.drawerAddUser = false;
                this.getList();
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                });
              }
            }).catch(() => {
              this.loading = false;
              this.$message({
                type: 'error',
                message: '添加失败!'
              });
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }
    },

    mounted() {
      this.getList();
    }
  };
</script>

<style scoped>
  .el-pagination {
    float: right;
    margin: 10px;
  }
</style>
